package org.yelongframework.servlet.http;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 默认实现
 * 
 * @since 1.0.0
 */
public class DefaultCookieSupport implements CookieSupport {

	@Override
	public String getCookie(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if (null == cookies) {
			return null;
		}
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(name)) {
				return cookie.getValue();
			}
		}
		return null;
	}

	@Override
	public void addCookie(HttpServletResponse response, String name, String value) {
		response.addCookie(new Cookie(name, value));
	}

	@Override
	public void removeCookie(HttpServletResponse response, String name) {
		Cookie newCookie = new Cookie(name, null); // 假如要删除名称为username的Cookie
		newCookie.setMaxAge(0); // 立即删除型
		newCookie.setPath("/"); // 项目所有目录均有效，这句很关键，否则不敢保证删除
		response.addCookie(newCookie); // 重新写入，将覆盖之前的
	}

	@Override
	public void clearCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies) {
			removeCookie(response, cookie.getName());
		}
	}

}
